package com.geovis.emergency.spd.controller.zwdd;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.geovis.common.auth.pojo.dto.AccessToken;
import com.geovis.common.auth.pojo.dto.LoginDTO;
import com.geovis.common.auth.props.AuthProperties;
import com.geovis.common.core.api.Result;
import com.geovis.common.core.util.WebUtil;
import com.geovis.emergency.spd.biz.system.service.ISystemUserService;
import com.geovis.emergency.spd.biz.zwdd.handler.ZwddEventCallbackHandler;
import com.geovis.emergency.spd.biz.zwdd.service.IZwddServcie;
import com.geovis.emergency.spd.entity.system.entity.SystemUser;
import com.geovis.emergency.spd.entity.zwdd.pojo.CallbackResult;
import com.geovis.emergency.spd.entity.zwdd.pojo.EmployeeAccount;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 海证通 前端控制器
 * </p>
 *
 * @author 王响
 * @since 2020-07-15
 */
@RestController
@RequestMapping("/zwdd")
@RequiredArgsConstructor
@Api(value = "海证通-相关接口", tags = "海证通-相关接口")
@Slf4j
@Validated
public class ZwddController {

    private final IZwddServcie zwddServcie;

    private final ZwddEventCallbackHandler zwddEventCallbackHandler;

    private final ISystemUserService systemUserService;

    private final AuthProperties authProperties;

    @ApiOperation(value = "同步海证通", notes = "同步海证通")
    @PostMapping("/synchronize")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "removeOldDeptAndUser", value = "是否清除旧组织机构信息和相关用户信息，默认false", example = "false", dataTypeClass = Boolean.class),
            @ApiImplicitParam(name = "removeOldUser", value = "是否清除旧的用户信息，默认false", example = "false", dataTypeClass = Boolean.class)
    })
    public Result<String> synchronize(Boolean removeOldDeptAndUser, Boolean removeOldUser) {
        zwddServcie.synchronize(removeOldDeptAndUser, removeOldUser);
        return Result.ok();
    }


    @ApiOperation(value = "注册事件", notes = "注册事件")
    @GetMapping("/registerListenerEvent")
    public Result registerListenerEvent() {
        zwddServcie.registerListenerEvent();
        return Result.ok();
    }

    @ApiOperation(value = "通过事件ID删除事件", notes = "通过事件ID删除事件")
    @GetMapping("/removeEvent/{eventCallbackId}")
    public Result removeEvent(@PathVariable("eventCallbackId") Long eventCallbackId) {
        zwddServcie.removeEvent(eventCallbackId);
        return Result.ok();
    }

    @ApiOperation(value = "查询事件列表", notes = "查询事件列表")
    @GetMapping("/getEventList")
    public Result getEventList() {
        return Result.ok(zwddServcie.getEventList());
    }

    @ApiOperation(value = "事件回调", notes = "事件回调")
    @PostMapping(value = "/callback")
    public CallbackResult callbackUrl(@RequestParam(name = "eventTag", required = false) String eventTag,
                                      @RequestParam(name = "dispatchId", required = false) String dispatchId,
                                      @RequestParam(name = "content", required = false) String content) {
        zwddServcie.eventCallBack(eventTag, content);
        return CallbackResult.ok();
    }

    @ApiOperation(value = "通过政务钉钉授权码登录", notes = "通过政务钉钉授权码登录")
    @PostMapping("/loginByAuthCode/{authCode}")
    public Result<AccessToken> loginByAuthCode(@PathVariable("authCode") String authCode) {
        log.info("---loginByAuthCode---authCode:"+authCode);
        EmployeeAccount employeeAccount = zwddServcie.authLogin(authCode);
        SystemUser systemUser = systemUserService.getById(employeeAccount.getEmployeeCode());
        if (ObjectUtil.isEmpty(systemUser)) {
            return Result.failed("系统还同步您的账号！请联系管理员!");
        }
        LoginDTO loginDTO = new LoginDTO();

        loginDTO.setUsername(systemUser.getUserName()).setPassword(authProperties.getDefaultPassword());
        String url = StrUtil.format("{}://localhost:{}{}", WebUtil.getRequest().getScheme(), WebUtil.getRequest().getServerPort(), WebUtil.getRequest().getContextPath());
        String result = HttpUtil.post(url.concat(authProperties.getLoginUrl()), JSONUtil.toJsonStr(loginDTO));
        log.info("---loginByAuthCode---url:"+url.concat(authProperties.getLoginUrl()));
        JSONObject resultJson = JSONUtil.parseObj(result);
        AccessToken data = JSONUtil.toBean(resultJson.getJSONObject("data"), AccessToken.class);
        return Result.ok(data);
    }

    @ApiOperation(value = "通过政务钉钉票据", notes = "通过政务钉钉票据")
    @GetMapping("/getTicket")
    public Result<JSONObject> getTicket() {
        return Result.ok(zwddServcie.getTicket());
    }

}
